/**
 * WebAssembly Calculator Worker
 * 用于在Worker线程中加载和运行WebAssembly计算模块
 */

const { parentPort } = require('worker_threads');

/**
 * 处理来自主线程的消息
 * @param {Object} message - 消息对象
 */
function handleMessage(message) {
    try {
        console.log('收到消息:', message);
        
        if (message.num1 && message.num2) {
            const { num1, num2 } = message;

            const Module = require('./dist/node/calculator.js');
            Module({wasmBinaryFile: 'dist/node/calculator.wasm'}).then(wasm => {
                const result = wasm.add(num1, num2);

                // 发送计算结果
                const response = {
                    type: 'result',
                    result: result
                };
                
                if (parentPort) {
                    parentPort.postMessage(response);
                } else if (typeof process !== 'undefined' && process.send) {
                    process.send(response);
                }
            })
        } else {
            throw new Error(`不支持的消息类型: ${message.type}`);
        }
    } catch (error) {
        console.error('处理消息时出错:', error);

        // 发送错误响应
        const errorResponse = {
            type: 'error',
            message: error.message
        };

        if (parentPort) {
            parentPort.postMessage(errorResponse);
        } else if (typeof process !== 'undefined' && process.send) {
            process.send(errorResponse);
        }
    }
}

// 设置消息监听器
if (parentPort) {
    parentPort.on('message', handleMessage);
} else if (typeof process !== 'undefined' && process.on) {
    process.on('message', handleMessage);
}

// 启动时初始化WebAssembly模块
console.log('Calculator Worker已启动，正在初始化WebAssembly模块...');
